package com.qiantu.phone.ui.activity;

import android.content.Intent;
import android.net.wifi.ScanResult;
import android.os.Parcelable;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.DeviceState;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.entity.SwitchBindActionBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.ui.adapter.PanelQRResultAdapter;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.ui.uiutil.DeviceType;
import com.qiantu.phone.utils.TopSmoothScroller;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PanelQRResultActivity  extends AppActivity {
    private RecyclerView list;
    private PanelQRResultAdapter adapter;
    private String panelSerialNo;
    private List<Map> bingingDatas;
    List<Map> successDatas;
    List<Map> failDatas;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_panel_qrresult;
    }

    @Override
    protected void initView() {
        getTitleBar().getRightView().setEnabled(false);
        list = findViewById(R.id.list);
        list.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new PanelQRResultAdapter(getContext());
        list.setAdapter(adapter);
    }

    @Override
    protected void initData() {
        String roomSerialNo = getIntent().getStringExtra("roomSerialNo");
        panelSerialNo = getIntent().getStringExtra("deviceSerialNo");
        ObjectMapper objectMapper = new ObjectMapper();
        Map analyseMap = null;
        try {
            String analyseData = getString("analyseData");
            if(analyseData == null  || analyseData.equals("")){
                toast("未识别到数据，请重新进行操作");
                finish();
                return;
            }
//            List<Map> analyseDatas = new ArrayList<>();
            analyseMap = objectMapper.readValue(analyseData, Map.class);
            List<Map> analyseDatas = (List<Map>) analyseMap.get("ret");
            if(analyseDatas == null){
                analyseDatas = new ArrayList<>();
            }
            successDatas = new ArrayList<>();
            failDatas = new ArrayList<>();
            List<SceneBean> sceneBeans = LLSceneDBManager.getInstance(getContext()).getSceneByRoom(roomSerialNo);
            List<DeviceBean> deviceBeans = LLDeviceDBManager.getInstance(getContext()).getDeviceByRoom(roomSerialNo);

            int keyNum = getKeyNum();
            for(int i = 0;i < keyNum;i++){
                Map data = new HashMap();
                data.put("name","按键"+(i+1));
                data.put("houseSerialNo", AppApplication.getInstance().getCurrentHouseSerialNo());
                data.put("switchSerialNo",panelSerialNo);
                data.put("switchKeyOpreate","1");
                data.put("switchKeyIndex",(i+1));
                if(i < analyseDatas.size()){
                    String name = analyseDatas.get(i).get("word").toString();
                    data.put("info",name);
                    Map actionMap = new HashMap();
                    Boolean isSame = false;
                    for(SceneBean sceneBean : sceneBeans){
                        if(sceneBean.getName().equals(name)){
                            data.put("bindType","2");
                            data.put("bindSerialNo",sceneBean.getSceneSerialNo());
                            data.put("actionType","0");
                            data.put("bindActionType","0");
                            actionMap.put("sceneSerialNo",sceneBean.getSceneSerialNo());
                            data.put("bindAction",actionMap);
                            isSame = true;
                            break;
                        }
                    }
                    if(!isSame){
                        for(DeviceBean deviceBean : deviceBeans){
                            if(deviceBean.getName().equals(name)){
                                data.put("bindType","1");
                                data.put("bindSerialNo",deviceBean.getDeviceSerialNo());
                                data.put("actionType","1");
                                actionMap.put("deviceSerialNo",deviceBean.getDeviceSerialNo());
                                DeviceState deviceState = new DeviceState();
                                if(deviceBean.getType().equals("light") || deviceBean.getType().equals("airconditioner") || deviceBean.getType().equals("floorheating") || deviceBean.getType().equals("freshair")){
                                    data.put("bindActionType","2");
                                    deviceState.getStatus().setPower(2);
//                                    data.put("bindAction",":{\"deviceState\":{\"status\":{\"power\":2}},\"deviceSerialNo\":\""+deviceBean.getDeviceSerialNo()+"\"}");
                                }else if(deviceBean.getType().equals("infrared")){
                                    data.put("bindActionType","0");
                                    deviceState.getStatus().setIrctrl(1);
//                                    data.put("bindAction",":{\"deviceState\":{\"status\":{\"irctrl\":1}},\"deviceSerialNo\":\""+deviceBean.getDeviceSerialNo()+"\"}");
                                }else if(deviceBean.getType().equals("wireless_433")){
                                    data.put("bindActionType","0");
                                    deviceState.getStatus().setWirelessctrl_433(1);
//                                    data.put("bindAction",":{\"deviceState\":{\"status\":{\"wirelessctrl_433\":1}},\"deviceSerialNo\":\""+deviceBean.getDeviceSerialNo()+"\"}");
                                }else if(deviceBean.getType().equals("wireless_315")){
                                    data.put("bindActionType","0");
                                    deviceState.getStatus().setWirelessctrl_315(1);
//                                    data.put("bindAction",":{\"deviceState\":{\"status\":{\"wirelessctrl_315\":1}},\"deviceSerialNo\":\""+deviceBean.getDeviceSerialNo()+"\"}");
                                }else if(deviceBean.getType().equals("curtain")){
                                    data.put("bindActionType","0");
                                    deviceState.getStatus().setStrokestate(1);
//                                    data.put("bindAction",":{\"deviceState\":{\"status\":{\"strokestate\":1}},\"deviceSerialNo\":\""+deviceBean.getDeviceSerialNo()+"\"}");
                                }
                                actionMap.put("deviceState",deviceState);
                                data.put("bindAction",actionMap);
                                isSame = true;
                                break;
                            }
                        }
                    }
                    if(isSame){
                        successDatas.add(data);
                    }else{
                        failDatas.add(data);
                    }
                }else{
                    data.put("info","未识别");
                    failDatas.add(data);
                }
            }
            buildData();
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    protected void buildData(){
        bingingDatas = new ArrayList<>();
        Map successMap = new HashMap();
        successMap.put("name","按键与名称");
        Map failMap = new HashMap();
        failMap.put("name","该房间无以下设备/场景");
        if(successDatas.size() > 0){
            getTitleBar().getRightView().setEnabled(true);
            successMap.put("data",successDatas);
            bingingDatas.add(successMap);
        }
        if(failDatas.size() > 0){
            failMap.put("data",failDatas);
            bingingDatas.add(failMap);
        }
        adapter.setData(bingingDatas);
    }

    protected int getKeyNum(){
        Intent intent = getIntent();
        String deviceType = intent.getStringExtra("type");
        if (deviceType.equals(DeviceType.WALL_SWITCH1.stringType)||deviceType.equals(DeviceType.WALL_SWITCH_S1.stringType)) {
            return 1;
        } else if (deviceType.equals(DeviceType.WALL_SWITCH2.stringType)  || deviceType.equals(DeviceType.WALL_SWITCH_S2.stringType)) {
            return 2;
        } else if (deviceType.equals(DeviceType.WALL_SWITCH3.stringType) ||deviceType.equals(DeviceType.WALL_SWITCH_S3.stringType)) {
           return 3;
        }else if (deviceType.equals(DeviceType.WALL_SWITCH4.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_J4.stringType)  || deviceType.equals(DeviceType.WALL_SWITCH_S4.stringType)) {
            return 4;
        } else if (deviceType.equals(DeviceType.WALL_SWITCH6.stringType)  || deviceType.equals(DeviceType.WALL_SWITCH_S6.stringType)) {
            return 6;
        }else if (deviceType.equals(DeviceType.WALL_SWITCH8.stringType) || deviceType.equals(DeviceType.WALL_SWITCH_J8.stringType)) {
            return 8;
        }
        return 0;
    }

    @Override
    public void onRightClick(View view) {
        if(failDatas.size() == 0){
            gotoAutoBinging();
        }else{
            showSaveDialog();
        }
    }

    protected void showSaveDialog(){
        new ConfirmHintDialog.Builder(this)
                .setLeftBtnText(getString(R.string.cancel))
                .setRightBtnText(getString(R.string.ok))
                .setContent("其中有"+failDatas.size()+"个按键的设备/场景未能正确识别，您确定继续嘛？")
                .setLeftBtnStrongHint(true)
                .setListener(new ConfirmHintDialog.OnListener() {
                    @Override
                    public void onLeftClick(BaseDialog dialog) {
                        dialog.dismiss();
                    }

                    @Override
                    public void onConfirm(BaseDialog dialog) {
                        dialog.dismiss();
                        gotoAutoBinging();
                    }
                })
                .show();
    }

    protected void gotoAutoBinging(){
        Intent thisIntent = getIntent();
        Intent intent = new Intent(getContext(), PanelQRBingingActivity.class);
        intent.putExtra("deviceSerialNo",thisIntent.getStringExtra("deviceSerialNo").toString());
        intent.putExtra("bingingDatas", (Serializable) successDatas);
        getContext().startActivity(intent);
    }

    public void gotoPanelBinging(Map map,int section,int row) {
        Intent intent = new Intent(getContext(), PanelBingingActivity.class);
        intent.putExtra("panelIndex", (Integer) map.get("switchKeyIndex"));
        intent.putExtra("panelSerialNo",map.get("switchSerialNo").toString());
        intent.putExtra("operateType",1);
        startActivityForResult(intent,new OnActivityCallback() {
            @Override
            public void onActivityResult(int resultCode, @Nullable Intent data) {
                if (resultCode == RESULT_OK){
                    Map map = (Map) data.getSerializableExtra("data");
                    if((successDatas.size() == 0  && section == 0) || section == 1){
                        failDatas.remove(row);
                        successDatas.add(map);
                        Collections.sort(successDatas,new Comparator<Map>() {
                            @Override
                            public int compare(Map lhs, Map rhs) {
                                if(Integer.parseInt(lhs.get("switchKeyIndex").toString()) > Integer.parseInt(rhs.get("switchKeyIndex").toString())){
                                    return 1;
                                }else{
                                    return -1;
                                }
                            }
                        });
                    }else{
                        successDatas.set(row,map);
                    }
                    buildData();
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }
}